package metr;

import connect.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class ProductManagementFrame extends JFrame {
    private JTable productTable;
    private DefaultTableModel tableModel;

    public ProductManagementFrame() {
        setTitle("商品信息管理");
        setSize(800, 600);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());

        // 顶部按钮区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        JButton addBtn = new JButton("添加商品");
        JButton editBtn = new JButton("修改商品");
        JButton deleteBtn = new JButton("删除商品");
        JButton refreshBtn = new JButton("刷新");

        buttonPanel.add(addBtn);
        buttonPanel.add(editBtn);
        buttonPanel.add(deleteBtn);
        buttonPanel.add(refreshBtn);

        panel.add(buttonPanel, BorderLayout.NORTH);

        // 中间表格区域
        tableModel = new DefaultTableModel();
        tableModel.addColumn("商品ID");
        tableModel.addColumn("商品名称");
        tableModel.addColumn("规格");
        tableModel.addColumn("单价");
        tableModel.addColumn("库存数量");
        tableModel.addColumn("供应商");
        tableModel.addColumn("最低库存");
        tableModel.addColumn("最高库存");

        productTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(productTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        add(panel);

        // 加载商品数据
        loadProductData();

        // 按钮事件
        addBtn.addActionListener(e -> {
            new AddProductDialog(this).setVisible(true);
        });

        editBtn.addActionListener(e -> {
            int selectedRow = productTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "请选择要修改的商品", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            int productId = (int) productTable.getValueAt(selectedRow, 0);
            new EditProductDialog(this, productId).setVisible(true);
        });

        deleteBtn.addActionListener(e -> {
            int selectedRow = productTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "请选择要删除的商品", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this, "确定要删除该商品吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                int productId = (int) productTable.getValueAt(selectedRow, 0);
                deleteProduct(productId);
                loadProductData();
            }
        });

        refreshBtn.addActionListener(e -> {
            loadProductData();
        });
    }

    private void loadProductData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM products")) {

            while (rs.next()) {
                Vector<Object> row = new Vector<>();
                row.add(rs.getInt("product_id"));
                row.add(rs.getString("name"));
                row.add(rs.getString("specification"));
                row.add(rs.getDouble("price"));
                row.add(rs.getInt("stock_quantity"));
                row.add(rs.getString("supplier"));
                row.add(rs.getInt("min_stock"));
                row.add(rs.getInt("max_stock"));
                tableModel.addRow(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载商品数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deleteProduct(int productId) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement("DELETE FROM products WHERE product_id = ?")) {

            stmt.setInt(1, productId);
            stmt.executeUpdate();

            JOptionPane.showMessageDialog(this, "商品删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "删除商品失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void refreshProductTable() {
        loadProductData();
    }
}

class AddProductDialog extends JDialog {
    private JTextField nameField;
    private JTextField specField;
    private JTextField priceField;
    private JTextField stockField;
    private JTextField supplierField;
    private JTextField minStockField;
    private JTextField maxStockField;

    public AddProductDialog(JFrame parent) {
        super(parent, "添加商品", true);
        setSize(400, 400);
        setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridLayout(8, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        panel.add(new JLabel("商品名称:"));
        nameField = new JTextField();
        panel.add(nameField);

        panel.add(new JLabel("规格:"));
        specField = new JTextField();
        panel.add(specField);

        panel.add(new JLabel("单价:"));
        priceField = new JTextField();
        panel.add(priceField);

        panel.add(new JLabel("库存数量:"));
        stockField = new JTextField();
        panel.add(stockField);

        panel.add(new JLabel("供应商:"));
        supplierField = new JTextField();
        panel.add(supplierField);

        panel.add(new JLabel("最低库存:"));
        minStockField = new JTextField("10");
        panel.add(minStockField);

        panel.add(new JLabel("最高库存:"));
        maxStockField = new JTextField("100");
        panel.add(maxStockField);

        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        panel.add(saveBtn);
        panel.add(cancelBtn);

        add(panel);

        saveBtn.addActionListener(e -> {
            try {
                String name = nameField.getText().trim();
                String spec = specField.getText().trim();
                double price = Double.parseDouble(priceField.getText().trim());
                int stock = Integer.parseInt(stockField.getText().trim());
                String supplier = supplierField.getText().trim();
                int minStock = Integer.parseInt(minStockField.getText().trim());
                int maxStock = Integer.parseInt(maxStockField.getText().trim());

                if (name.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "商品名称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement stmt = conn.prepareStatement(
                             "INSERT INTO products (name, specification, price, stock_quantity, supplier, min_stock, max_stock) VALUES (?, ?, ?, ?, ?, ?, ?)")) {

                    stmt.setString(1, name);
                    stmt.setString(2, spec);
                    stmt.setDouble(3, price);
                    stmt.setInt(4, stock);
                    stmt.setString(5, supplier);
                    stmt.setInt(6, minStock);
                    stmt.setInt(7, maxStock);

                    stmt.executeUpdate();

                    JOptionPane.showMessageDialog(this, "商品添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    ((ProductManagementFrame) getParent()).refreshProductTable();
                    dispose();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "添加商品失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelBtn.addActionListener(e -> {
            dispose();
        });
    }
}

class EditProductDialog extends JDialog {
    private JTextField nameField;
    private JTextField specField;
    private JTextField priceField;
    private JTextField stockField;
    private JTextField supplierField;
    private JTextField minStockField;
    private JTextField maxStockField;
    private int productId;

    public EditProductDialog(JFrame parent, int productId) {
        super(parent, "修改商品", true);
        this.productId = productId;
        setSize(400, 400);
        setLocationRelativeTo(parent);

        JPanel panel = new JPanel(new GridLayout(8, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        panel.add(new JLabel("商品名称:"));
        nameField = new JTextField();
        panel.add(nameField);

        panel.add(new JLabel("规格:"));
        specField = new JTextField();
        panel.add(specField);

        panel.add(new JLabel("单价:"));
        priceField = new JTextField();
        panel.add(priceField);

        panel.add(new JLabel("库存数量:"));
        stockField = new JTextField();
        panel.add(stockField);

        panel.add(new JLabel("供应商:"));
        supplierField = new JTextField();
        panel.add(supplierField);

        panel.add(new JLabel("最低库存:"));
        minStockField = new JTextField();
        panel.add(minStockField);

        panel.add(new JLabel("最高库存:"));
        maxStockField = new JTextField();
        panel.add(maxStockField);

        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        panel.add(saveBtn);
        panel.add(cancelBtn);

        add(panel);

        // 加载商品数据
        loadProductData();

        saveBtn.addActionListener(e -> {
            try {
                String name = nameField.getText().trim();
                String spec = specField.getText().trim();
                double price = Double.parseDouble(priceField.getText().trim());
                int stock = Integer.parseInt(stockField.getText().trim());
                String supplier = supplierField.getText().trim();
                int minStock = Integer.parseInt(minStockField.getText().trim());
                int maxStock = Integer.parseInt(maxStockField.getText().trim());

                if (name.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "商品名称不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                try (Connection conn = DBUtil.getConnection();
                     PreparedStatement stmt = conn.prepareStatement(
                             "UPDATE products SET name=?, specification=?, price=?, stock_quantity=?, supplier=?, min_stock=?, max_stock=? WHERE product_id=?")) {

                    stmt.setString(1, name);
                    stmt.setString(2, spec);
                    stmt.setDouble(3, price);
                    stmt.setInt(4, stock);
                    stmt.setString(5, supplier);
                    stmt.setInt(6, minStock);
                    stmt.setInt(7, maxStock);
                    stmt.setInt(8, productId);

                    stmt.executeUpdate();

                    JOptionPane.showMessageDialog(this, "商品修改成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    ((ProductManagementFrame) getParent()).refreshProductTable();
                    dispose();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "修改商品失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelBtn.addActionListener(e -> {
            dispose();
        });
    }

    private void loadProductData() {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM products WHERE product_id = ?")) {

            stmt.setInt(1, productId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                nameField.setText(rs.getString("name"));
                specField.setText(rs.getString("specification"));
                priceField.setText(String.valueOf(rs.getDouble("price")));
                stockField.setText(String.valueOf(rs.getInt("stock_quantity")));
                supplierField.setText(rs.getString("supplier"));
                minStockField.setText(String.valueOf(rs.getInt("min_stock")));
                maxStockField.setText(String.valueOf(rs.getInt("max_stock")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载商品数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
